package com.informatics.polymer.server.Polymerisation;

import java.util.List;

import org.xmlcml.cml.element.CMLAtom;
import org.xmlcml.cml.element.CMLBond;
import org.xmlcml.cml.element.CMLMolecule;

/**
 * Class to deal with R-R bonds, essentially will delete the RR bond and RR
 * atoms find the neighbour atoms then form a bond between the neighbour atoms
 * and break R1-X1 and R2-X2 bonds.
 * 
 * @author Ed Cannon
 * @version 1.0
 */

public class RRBonds {
	/**
	 * repeatUnitMolecule is a CMLMolecule representation of the repeat unit.
	 */
	private CMLMolecule repeatUnitMolecule;
	/**
	 * First CMLAtom with R-Element in R-R bond.
	 */
	private CMLAtom r1;
	/**
	 * Second CMLAtom with R-Element in R-R bond.
	 */
	private CMLAtom r2;
	/**
	 * Neighbour CMLAtom to r1.
	 */
	private CMLAtom x1;
	/**
	 * Neighbour CMLAtom to r2.
	 */
	private CMLAtom x2;

	/**
	 * Creates RRBonds object given a CMLBond, and CMLMolecule.
	 * 
	 * @param cb
	 *            -Represents an R-R bond using CMLBond.
	 * @param m
	 *            - CMLMolecule representation of the repeat unit molecule.
	 */
	RRBonds(final CMLBond cb, final CMLMolecule m) {
		this.repeatUnitMolecule = m;
		r1 = cb.getAtom(0);
		r2 = cb.getAtom(1);
	}

	/**
	 * Sets neighbouring atoms to R-R bonds.
	 */
	public final void automaticallySetX1X2() {
		List<CMLAtom> neighboursR1 = r1.getLigandAtoms();
		List<CMLAtom> neighboursR2 = r2.getLigandAtoms();
		for (int i = 0; i < neighboursR1.size(); i++) {
			if (!neighboursR1.get(i).getElementType().equals("R")) {
				// } else {
				x1 = neighboursR1.get(i);
			}
		}
		// Iterate over the R2 neighbour list
		for (int i = 0; i < neighboursR2.size(); i++) {
			if (!neighboursR2.get(i).getElementType().equals("R")) {
				// } else {
				x2 = neighboursR2.get(i);
			}
		}
	}

	/**
	 * Return CMLAtom neighbouring R1 in R-R bond.
	 * 
	 * @return X1
	 */
	public final CMLAtom getX1() {
		return x1;
	}

	/**
	 * Return CMLAtom neighbouring R2 in R-R bond.
	 * 
	 * @return X2
	 */
	public final CMLAtom getX2() {
		return x2;
	}

	/**
	 * Creates a CMLBond between X1 and X2.
	 */
	public final void createX1X2Bond() {
		CMLBond cmlBond = new CMLBond();
		cmlBond.setAttribute("atomRefs2", x1.getId() + " " + x2.getId());
		cmlBond.setId(x1.getId() + " " + x2.getId());
		cmlBond.setOrder("1");
		repeatUnitMolecule.addBond(cmlBond);

	}

	/**
	 * Deletes R groups and R1-X1, R2-X2 and R1-R2 bonds.
	 */
	public final void deleteRgroupsAndBonds() {
		repeatUnitMolecule.deleteAtom(r1);
		repeatUnitMolecule.deleteAtom(r2);
		repeatUnitMolecule.deleteBond(r1, r2);
		repeatUnitMolecule.deleteBond(r1, x1);
		repeatUnitMolecule.deleteBond(r2, x2);
	}

	/**
	 * Returns updated repeat unit molecule.
	 * 
	 * @return repeatUnitMolecule
	 */
	public final CMLMolecule getUpdatedMolecule() {
		return repeatUnitMolecule;
	}
}